/*
 * @Author: gao_m3
 * @Date: 2022-06-28 15:35:24
 * @LastEditors: 
 * @LastEditTime: 2022-07-15 10:32:58
 * @Descripttion: 
 */
import {
  BentleyCloudRpcManager,
  IModelReadRpcInterface,
  IModelWriteRpcInterface,
  IModelTileRpcInterface,
  SnapshotIModelRpcInterface,
  RpcInterface,
  RpcConfiguration,
  WebAppRpcRequest
} from '@bentley/imodeljs-common'
const requestConfig = {
  origin: 'http://10.215.142.120:5566/',
  token: ''
}
WebAppRpcRequest.prototype.performFetch = async function () {
  const requestClass = this.supplyRequest()
  const fetchFunction = this.supplyFetch()
  const path = new URL(this.path, requestConfig.origin)
  if (this._pathSuffix) {
    const params = new URLSearchParams()
    params.set('parameters', this._pathSuffix)
    path.search = `?${params.toString()}`
  }
  // eslint-disable-next-line new-cap
  const request = new requestClass(path.toString(), this._request)
  const response = await fetchFunction(request)
  this._response = response
  this.metadata.status = response.status
  return response.status
}
RpcInterface.prototype.forward = async function (parameters) {
  const CURRENT_REQUEST = Symbol.for(
    '@bentley/imodeljs-common/RpcRequest/__current__'
  )
  const parametersCompat =
    arguments.length === 1 && typeof parameters === 'object'
      ? parameters
      : arguments
  const parametersArray = Array.isArray(parametersCompat)
    ? parametersCompat
    : Array.prototype.slice.call(parametersCompat)
  const operationName = parametersArray.pop()

  const request = new this.configuration.protocol.requestType(
    this,
    operationName,
    parametersArray
  )
  // request.setHeader('Fawkes-Auth', localStorage.getItem('access_token'))
  request.submit()
  this[CURRENT_REQUEST] = request
  return request.response
}

export default class RpcHandle {
  static init () {
    RpcConfiguration.developmentMode = true

    const rpcInterfaces = RpcHandle.getRpcInterfaces()
    const rpcParams = {
      info: {
        title: 'cbe' + '/cybertwin-dev' + '/SimpleViewApp',
        version: 'v1.0'
      }
    }
    BentleyCloudRpcManager.initializeClient(
      rpcParams,
      rpcInterfaces
    )
  }

  static getRpcInterfaces () {
    return [
      IModelReadRpcInterface,
      IModelTileRpcInterface,
      IModelWriteRpcInterface,
      SnapshotIModelRpcInterface
    ]
  }
}
